package com.filldream.fastboot.common.util.entity.wxpay;

import cn.hutool.core.util.StrUtil;
import com.filldream.fastboot.common.util.PayUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author RickSun
 * @version 1.0
 * @data 2020-11-26 18:05
 * @description WxPaySTO
 */
public class WxPaySTO {

    /**
     * @author RickSun
     * @Description 对象转Map
     **/
    public Map<String, String> toMap() {
        String[] fieldNames = getFiledNames(this);
        HashMap<String, String> map = new HashMap<String, String>(fieldNames.length);
        for (String name : fieldNames) {
            String value = (String) getFieldValueByName(name, this);
            if (StrUtil.isNotEmpty(value)) {
                map.put(name, value);
            }
        }
        return map;
    }

    /**
     * @author RickSun
     * @Description 微信支付参数
     **/
    public Map<String, String> sign(Map<String, String> param,String signKey) {
        String paramStr = PayUtil.build(param, "key", signKey);
        String sign = PayUtil.sign(paramStr);
        param.put("sign",sign);
        return param;
    }

    /**
     * 获取属性名数组
     * @param obj 对象
     * @return 返回对象属性名数组
     */
    public String[] getFiledNames(Object obj) {
        Field[] fields = obj.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }

    /**
     * 根据属性名获取属性值
     * @param fieldName 属性名称
     * @param obj       对象
     * @return 返回对应属性的值
     */
    public Object getFieldValueByName(String fieldName, Object obj) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = new StringBuffer().append("get")
                    .append(firstLetter)
                    .append(fieldName.substring(1))
                    .toString();
            Method method = obj.getClass().getMethod(getter);
            return method.invoke(obj);
        } catch (Exception e) {
            return null;
        }
    }


}
